/*
 * AIEngine a new generation network intrusion detection system.
 *
 * Copyright (C) 2013-2023  Luis Campo Giralte
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 *
 * Written by Luis Campo Giralte <luis.camp0.2009@gmail.com>
 *
 */
#include "VxLanProtocol.h"
#include <iomanip>

namespace aiengine {

bool VxLanProtocol::check(const Packet &packet){

	int length = packet.getLength();

	if (length >= header_size) {
		setHeader(packet.getPayload());

		if (header_->flags & 0x08) {
			++total_valid_packets_;
			return true;
		}
	}
	++total_invalid_packets_;
	return false;
}

void VxLanProtocol::processFlow(Flow *flow) {

	CPUCycle cycles(&total_cpu_cycles_);
        int bytes = flow->packet->getLength();
        total_bytes_ += bytes;
        ++total_packets_;

        if (!mux_.expired()&&(bytes >= header_size)) {
		// Check the VNI and forward the packet
                MultiplexerPtr mux = mux_.lock();

                Packet *packet = flow->packet;
		setHeader(packet->getPayload());

                Packet gpacket(*packet);

		// Sets the Tag for the packet
		gpacket.setTag(getVni());

                mux->setNextProtocolIdentifier(0);
                mux->forward(gpacket);

		if (gpacket.haveEvidence())
			flow->setEvidence(gpacket.haveEvidence());
         }
}

void VxLanProtocol::statistics(std::basic_ostream<char> &out, int level, int32_t limit) const {

	showStatisticsHeader(out, level);

	if (level > 5) {
		if (mux_.lock())
			mux_.lock()->statistics(out);
		if (flow_forwarder_.lock())
			flow_forwarder_.lock()->statistics(out);
	}
}

void VxLanProtocol::statistics(Json &out, int level) const {

	showStatisticsHeader(out, level);
}

CounterMap VxLanProtocol::getCounters() const {
	CounterMap cm;

        cm.addKeyValue("packets", total_packets_);
        cm.addKeyValue("bytes", total_bytes_);

        return cm;
}

void VxLanProtocol::resetCounters() {

	reset();
}


} // namespace aiengine
